package com.managermype.business;

import java.util.Calendar;
import java.util.Set;

import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.managermype.dao.interfaces.UserDao;
import com.managermype.domain.Departament;
import com.managermype.domain.Enterprise;
import com.managermype.domain.Role;
import com.managermype.domain.User;
import com.managermype.exception.ManagerMypeException;

/**
 * 
 * @author juandiego
 *
 */
@Service
public class UserBusiness {

	@Autowired
	UserDao userDao;

	@Autowired
	User user;

	/**
	 * 
	 * @param username
	 * @param password
	 * @return
	 * @throws ManagerMypeException
	 */
	public User loginUser(String username, String password) throws ManagerMypeException {
		try {
			return userDao.login(username, password);
		}
		catch (HibernateException e) {
			// Because it's a SQLException throws from a Store Procedure
			throw new ManagerMypeException(e.getCause().getMessage());
		}
		catch (Exception e) {
			throw new ManagerMypeException(e.getMessage());
		}
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @param firstname
	 * @param lastname
	 * @param motherLastname
	 * @param birthdate
	 * @param identity
	 * @param gender
	 * @param active
	 * @param myRoles
	 * @param myEnterprise
	 * @param myDepartament
	 * @return
	 * @throws ManagerMypeException
	 */
	public User insertUser(String username, String password, String firstname, String lastname,
			String motherLastname, Calendar birthdate, String identity, char gender, boolean active,
			Set<Role> myRoles, Enterprise myEnterprise, Departament myDepartament)
			throws ManagerMypeException {
		
		user.setFirstname(firstname);
		user.setLastname(lastname);
		user.setMotherLastname(motherLastname);
		user.setBirthdate(birthdate);
		user.setUsername(username);
		user.setPassword(password);
		user.setIdentity(identity);
		user.setGender(gender);
		user.setActive(active);
		user.setMyRoles(myRoles);
		user.setMyDepartament(myDepartament);
		user.setMyEnterprise(myEnterprise);
		
		try {
			return userDao.insert(user);
		}
		catch (HibernateException e) {
			throw new ManagerMypeException(e.getMessage());
		}
		catch (Exception e) {
			throw new ManagerMypeException(e.getMessage());
		}
	}
	
	/**
	 * 
	 * @param username
	 * @return
	 * @throws ManagerMypeException
	 */
	public User getUserByUsername(String username) throws ManagerMypeException{
		try {
			return userDao.getByUsername(username);
		}
		catch (HibernateException e) {
			throw new ManagerMypeException(e.getMessage());
		}
		catch (Exception e) {
			throw new ManagerMypeException(e.getMessage());
		}
	}
}
